// AI服务接口
import { DIFFICULTY } from '../config/gameConfig'

// AI模型类型
export const AI_MODEL = {
  DOUBAN: 'douban',
  DEEPSEEK: 'deepseek'
}

// AI响应格式化函数
const formatAIResponse = (response) => {
  try {
    // 这里需要根据实际AI返回的数据格式进行解析
    return {
      from: response.from,
      to: response.to,
      piece: response.piece
    }
  } catch (error) {
    console.error('AI响应格式化错误:', error)
    return null
  }
}

// 构建AI提示词
const buildPrompt = (gameState, difficulty) => {
  return `当前棋局状态：${JSON.stringify(gameState)}\n
请根据${difficulty}难度等级，分析当前局势并给出下一步最佳走法。\n
请以JSON格式返回，包含：\n1. 起始位置 (from)\n2. 目标位置 (to)\n3. 移动的棋子 (piece)`
}

// 豆包AI接口
export const doubanAI = async (gameState, difficulty) => {
  try {
    const response = await fetch('https://ark.cn-beijing.volces.com/api/v3/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': '19d72b56-5003-4c54-8698-1667c3f9ee1d'
      },
      body: JSON.stringify({
        model: 'ep-20250211154131-hh564',
        messages: [
          {
            role: 'system',
            content: '你是一个中国象棋AI助手，负责分析棋局并给出最佳走法。'
          },
          {
            role: 'user',
            content: buildPrompt(gameState, difficulty)
          }
        ]
      })
    })
    const data = await response.json()
    return formatAIResponse(data)
  } catch (error) {
    console.error('豆包AI调用错误:', error)
    return null
  }
}

// DeepSeek AI接口
export const deepseekAI = async (gameState, difficulty) => {
  try {
    // TODO: 实现DeepSeek API调用
    // const response = await fetch('DeepSeek API地址', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //     'Authorization': '你的DeepSeek API密钥'
    //   },
    //   body: JSON.stringify({
    //     prompt: buildPrompt(gameState, difficulty)
    //   })
    // })
    // const data = await response.json()
    // return formatAIResponse(data)
    throw new Error('DeepSeek AI接口尚未实现')
  } catch (error) {
    console.error('DeepSeek AI调用错误:', error)
    return null
  }
}

// 获取AI走法
export const getAIMove = async (model, gameState, difficulty) => {
  switch (model) {
    case AI_MODEL.DOUBAN:
      return await doubanAI(gameState, difficulty)
    case AI_MODEL.DEEPSEEK:
      return await deepseekAI(gameState, difficulty)
    default:
      console.error('未知的AI模型类型')
      return null
  }
}